from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi
import sys
import os

PORT = int (sys.argv[1])
KEY = sys.argv[2]

class PennyworthHandler (BaseHTTPRequestHandler):
	def do_GET (self):
		print (self.path)

		query = { }
		
		sensor_name = None
		sensor_value = None
		sensor_duration = "0"
		
		try:
			query = cgi.parse_qs (self.path.split ("?")[1])
			
			sensor_name = query["name"][0]			
			sensor_value = query["value"][0]			
			key = query["key"][0]			
			
			try:
				sensor_duration = query["duration"][0]			
			except KeyError:
				pass

			self.send_response (200)
			self.send_header ("Content-type", "text/xml")
			self.end_headers ()
			self.wfile.write ("<ok />")
			
			print ("name = " + sensor_name + "; value = " + sensor_value + "; duration = " + sensor_duration)
			
			if (key == KEY):
				print ("got key")
				
				command = "tell application \\\"Pennyworth\\\" to log \\\"" + sensor_value + "\\\""
				
				if (sensor_duration != "0"):
					command += " with duration " + sensor_duration
					
				command += " from sensor \\\"" + sensor_name + "\\\""
				
				os.system ("/usr/bin/osascript -e \"" + command + "\"")
		except KeyError:
			self.send_response (500)
			self.send_header ("Content-type", "text/xml")
			self.end_headers ()
			self.wfile.write ("<error message=\"Check that the 'name' and 'value' arguments were sent.\" />")
		except IndexError:
			self.send_response (404)
			self.send_header ("Content-type", "text/plain")
			self.end_headers ()
			self.wfile.write ("Unknown path '" + self.path + "'.")
		
		# Post observation to Pennyworth via AppleScript
	def do_POST (self):
		self.do_GET ()
	
def main ():
	try:
		server = HTTPServer (("", PORT), PennyworthHandler)
		print ("started server");
		server.serve_forever ()
	except KeyboardInterrupt:
		print ("stopping server...")
		server.socket.close ()
		
if __name__ == "__main__":
	main ()
	